package com.mmz.gulimall.product.service.impl;

import com.mmz.gulimall.product.service.CategoryBrandRelationService;
import com.mmz.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mmz.common.utils.PageUtils;
import com.mmz.common.utils.Query;

import com.mmz.gulimall.product.dao.CategoryDao;
import com.mmz.gulimall.product.entity.CategoryEntity;
import com.mmz.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
//    @Autowired
//    StringRedisTemplate redisTemplate;
    

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查处所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子结构
        //2.1找到所有的一级分类
        List<CategoryEntity> collect = entities.stream().filter(entity ->
                entity.getParentCid() == 0
        ).map((memu) -> {
            memu.setChildren(getChildrens(memu, entities));
            return memu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void removeMenus(Long[] catIds) {
        //1. todo 判断是否有数据依赖该菜单
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @CacheEvict: 失效模式
     * @param category
     */
    @CacheEvict(value = "category",key = "'getCategoryService'")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable({"category"})
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
    }

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2Vo>> getCategoryService() {
        System.out.println("getCategoryService方法被调用");
        /**
         * 1、空结果缓存：解决缓存穿透问题
         * 2、设置过期时间（随机加值）：解决缓存雪崩问题
         * 3、加锁：解决缓存击穿问题
         */
//        //1.从缓存中获取数据
//        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
//        if (StringUtils.isEmpty(catalogJSON)) {
            //如果不存在，便想数据库中查询，并将返回结果放入缓存中
            Map<String, List<Catelog2Vo>> categoryForDbService = getCategoryForDbService();
            //将结果的Java对象转换为json
//            String s = JSON.toJSONString(categoryForDbService);
//            redisTemplate.opsForValue().set("catalogJSON", s);
            return categoryForDbService;
//        }
//        //将查询出的json串转化为指定的Java对象
//        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {});
//        return result;
    }

    /**
     * 从数据库中获取分类数据
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCategoryForDbService() {
        //获取所有分类
        List<CategoryEntity> categoryAll = baseMapper.selectList(null);
        //获取去所有的2级分类
        List<CategoryEntity> category2All = categoryAll.stream().filter(item -> item.getCatLevel() == 2).collect(Collectors.toList());
        //获取去所有的3级分类
        List<CategoryEntity> category3All = categoryAll.stream().filter(item -> item.getCatLevel() == 3).collect(Collectors.toList());
        Map<String, List<Catelog2Vo>> collect = null;
        if (categoryAll != null) {
            /**封装的格式为｛
             *      “1”：Array,
             *      “2”：Array,
             *      “3”：Array
             */
            collect = categoryAll.stream()
                    .filter(category -> category.getCatLevel() == 1)
                    .collect(Collectors
                            .toMap(k -> k.getCatId().toString(),
                                    //封装2级分类
                                    v -> {
                                        return category2All.stream()
                                                .filter(item -> item.getParentCid().equals(v.getCatId()))
                                                .map(val -> new Catelog2Vo(
                                                        v.getCatId().toString(),
                                                        category3All.stream()
                                                                  .filter(item -> item.getParentCid().equals(val.getCatId()))
                                                                .map(val3 -> {
                                                                            return new Catelog2Vo.Catelog3Vo(val3.getParentCid().toString(), val3.getCatId().toString(), val3.getName());
                                                                        }
                                                                )
                                                                .collect(Collectors.toList()),
                                                        val.getCatId().toString(),
                                                        val.getName()))
                                                .collect(Collectors.toList());
                                    }

                            ));
        }
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;

    }
}
